/*
    jME Terra package. A Terrain Engine for the Java Monkey Engine.
    Copyright (C) 2005-2006,  Tijl Houtbeckers
    
    **** LICENSE: ****

	This library is free software; you can redistribute it and/or
	modify it under the terms of the GNU Lesser General Public
	License as published by the Free Software Foundation,
	version 2.1.
	
	This library is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
	Lesser General Public License for more details.
	
	You should have received a copy of the GNU Lesser General Public
	License along with this library; if not, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

	**** CONTACT: ****

    I can be reached through the jmonkeyengine.com forums (user "llama"), 
    or the jmonkeyengine.com contact page:
    jmonkeyengine.com/index.php?option=com_contact&task=view&contact_id=5           

*/

/**
 * @author Tijl Houtbeckers
 */

package org.llama.jmex.terra.format;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;

import org.llama.jmex.terra.MapStore;

import com.jmex.terrain.util.AbstractHeightMap;

/*
 * Simple implentation of a map source based on one large
 * AbstractHeightMap 
 */
public class JMEXMapStore implements MapStore{
	
	private AbstractHeightMap ahm;
	private int mapsize;
	public JMEXMapStore(AbstractHeightMap ahm, int mapsize) {
		this.ahm = ahm;
		this.mapsize = mapsize;		
	}

	public ByteBuffer loadMap(int x, int y) throws IOException {
		int middle = ahm.getSize() / 2;
		int startx = middle+x*mapsize;
		int starty = middle+y*mapsize;
		
//		System.out.println("req: "+x+":"+y+" startx: "+startx+":"+starty);
		// this signals it needs a new map
		if (startx+mapsize > ahm.getSize() || startx < 0 || 
				starty+mapsize>ahm.getSize() || starty < 0)
			throw new IOException("Outside of range");
		
//		System.out.println("go!");
		ByteBuffer buf = createMap(x, y, mapsize*mapsize);
		buf.rewind();
		IntBuffer intbuf = buf.asIntBuffer();
		int[] hm = ahm.getHeightMap();
		for (int k = starty; k < starty+mapsize; k++) {
			intbuf.put(hm, (k * ahm.getSize()) + startx, mapsize);
		}
		intbuf.rewind();
//		System.out.println("done!");
		return buf;
	}

	public ByteBuffer createMap(int x, int y, int size) throws IOException {
		if (size != mapsize*mapsize)
			throw new IOException("Compressed maps not implemented.");
		return ByteBuffer.allocate(size*4);
	}

	public void saveMap(int x, int y, ByteBuffer buf) throws IOException {
		throw new IOException("Saving not implemented.");
	}
	
}
